package com.cn.qgx428.lazydiary.mWidget

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import com.cn.qgx428.lazydiary.R

/**
 * Created by qinguanxiong on 2018/3/1.
 */
class MTitleBar: RelativeLayout {

    private lateinit var back: ImageView
    private lateinit var title: TextView
    private lateinit var mainLayout: RelativeLayout
    private lateinit var titleString: String
    private var mColor = R.color.colorAccent
    private var textColor = R.color.mWhite

    constructor(context: Context): super(context){
        initView(context)
    }

    constructor(context: Context, attrs: AttributeSet): super(context,attrs){
        initTypedArray(context, attrs)
        initView(context)
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int): super(context,attrs,defStyleAttr){
        initTypedArray(context, attrs)
        initView(context)
    }

    @SuppressLint("ResourceAsColor")
    private fun initView(context: Context) {
        LayoutInflater.from(context).inflate(R.layout.view_customtitle,this, true)
        back = findViewById(R.id.customTitle_back)
        title = findViewById(R.id.customTitle_title)
        mainLayout = findViewById(R.id.customTitle_mainLayout)

        mainLayout.setBackgroundColor(mColor)
        title.setTextColor(textColor)
        title.text = titleString
    }

    @SuppressLint("ResourceAsColor")
    private fun initTypedArray(context: Context, attrs: AttributeSet){
        val typeds = context.obtainStyledAttributes(attrs, R.styleable.MTitleBar)
        mColor = typeds.getColor(R.styleable.MTitleBar_bg, context.resources.getColor(R.color.colorAccent))
        textColor = typeds.getColor(R.styleable.MTitleBar_titleColor, context.resources.getColor(R.color.mWhite))
        titleString = typeds.getString(R.styleable.MTitleBar_text)
        if (titleString.equals("") || titleString==null){
            titleString  = "懒人日记"
        }
        typeds.recycle()
    }

    fun setTitle(titleName: String){
        title.text = titleName
    }

    fun setTitleColor(color: Int){
        title.setTextColor(color)
    }

    fun setBackOnClickListener(f: ()->Unit){
        back.setOnClickListener({
            f()
        })
    }

    fun setBackIcon(id: Int){
        back.setImageResource(id)
    }

    fun setBackGroundColor(color: Int){
        mainLayout.setBackgroundColor(color)
    }
}